<?php

namespace Libraries\OAuth2Client;

use Models\User;
use RunTimeException;

class WechatOAuth2Client extends OAuth2Client
{
    private $openid;

    public function redirectToAuthorize($redirect_uri, $scope = 'snsapi_userinfo', $state = null)
    {
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?';

        $params = [
            'appid' => $this->clientId,
            'redirect_uri' => $redirect_uri,
            'response_type' => 'code',
            'scope' => $scope,
            'state' => $state,
        ];

        header('Location: '.$url.http_build_query($params).'#wechat_redirect');
    }

    public function getAccessToken($code)
    {
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token';
        $params = [
            'appid' => $this->clientId,
            'secret' => $this->clientSecret,
            'code' => $code,
            'grant_type' => 'authorization_code',
        ];
        $result = curl_get($url.'?'.http_build_query($params));
        $response = json_decode($result);
        if( property_exists($response, 'access_token')) {
            $this->openid = $response->openid;
            return array(
                'access_token' => $response->access_token,
                'expires_in' => $response->expires_in,
                'user_id' => $response->openid,
                'refresh_token' => $response->refresh_token,
                'refresh_token_expires_in' => 86400*30,
            );
        } else {
            throw new RunTimeException("get access_token error".$response->errmsg, $response->errcode);
            
        }
    }

    public function refreshToken($refresh_token)
    {
        $url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token';
        $params = [
            'appid' => $this->client_id,
            'grant_type' => 'refresh_token',
            'refresh_token' => $refresh_token
        ];

        $result = curl_post($url, $param);
        $response = json_decode($result);
        if( property_exists($response, 'access_token')) {
            $this->openid = $response->openid;
            return array(
                'access_token' => $response->access_token,
                'expires_in' => $response->expires_in,
                'user_id' => $response->openid,
                'refresh_token' => $response->refresh_token,
                'refresh_token_expires_in' => 86400*30,
            );
        } else {
            throw new RunTimeException("get access_token error".$response->errmsg, $response->errcode);
            
        }
    }

    public function getUserInfo($access_token)
    {
        $url = 'https://api.weixin.qq.com/sns/userinfo';

        $params = [
            'access_token' => $access_token,
            'openid' => $this->openid,
            'lang' => 'zh_CN'
        ];

        $result = curl_get($url.'?'.http_build_query($params));
         $response = json_decode($result);
        if( property_exists($response, 'nickname')) {
            return $response;
        } else {
            throw new RunTimeException("get userinfo error".$response->errmsg, $response->errcode);
        }
    }

    public function saveUser(User $user, $userInfo)
    {
        if (!$user->where('openid_weixin', $userInfo->openid)->get_one()) {
            $user['openid_weixin'] = $userInfo->openid;
            $user['username'] = $userInfo->nickname;
            $user['nickname'] = $userInfo->nickname;
            $user['avatar'] = $userInfo->headimgurl;
            $user['create_at'] = date('Y-m-d H:i:s');
            if (!$user->add()) {
                $error = get_instance()->db->error();
                throw new RunTimeException("save user failed".$error['message'], $error['code']);
            }
        }

        return $user;
    }
}